﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using VoiceMessager.Stream;

namespace VoiceMessager
{
	public partial class Form1 : Form
	{
		private Udp _udp;
		private VerifyMethod _verifyMethod;
		private List<HistoryItem> historyItems = new List<HistoryItem>();
		private SynchronizationContext _synchronizationContext;
		public Form1()
		{
			InitializeComponent();
			_synchronizationContext = SynchronizationContext.Current;
		}

		private void 配置帧ToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void 语音帧ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			new VoiceFrameForm(_verifyMethod,_udp).Show();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			if (toolStripComboBox1.ComboBox != null)
				toolStripComboBox1.ComboBox.DataSource = typeof(VerifyMethod).GetEnumNames();
		}

		private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			_verifyMethod = (VerifyMethod) Enum.Parse(typeof(VerifyMethod), toolStripComboBox1.Text);
		}

		private void toolStripComboBox1_TextChanged(object sender, EventArgs e)
		{
			_verifyMethod = (VerifyMethod)Enum.Parse(typeof(VerifyMethod), toolStripComboBox1.Text);
		}

		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			_udp = new Udp(new IPEndPoint(IPAddress.Parse(toolStripTextBox1.Text), Convert.ToInt32(toolStripTextBox2.Text)));
			toolStripTextBox1.Enabled = false;
			toolStripTextBox2.Enabled = false;
			_udp.OnRecive += _udp_OnRecive;
		}

		private void _udp_OnRecive(object sender, OnReciveEventArgs e)
		{
			if (e.ReviceBytes.Length != 10) return;
			var x = new ReplyStream
			{
				Header = e.ReviceBytes.Take(3).ToArray(),
				Order = e.ReviceBytes[3],
				DataLength = e.ReviceBytes[4],
				VerifyData = e.ReviceBytes.Skip(5).Take(2).ToArray(),
				State = e.ReviceBytes[7],
				ReplyData = e.ReviceBytes[8],
				Stop = e.ReviceBytes[9]
			};

			historyItems.Add(new HistoryItem
			{
				Id=1,
				Class = "接收",
				Data = "数据",
				Status = "成功",
				Stream = e.ReviceBytes,
				Time = DateTime.Now
			});
			_synchronizationContext.Send(state =>
			{
				ListViewItem item = new ListViewItem();
				item.Text = DateTime.Now.ToString("hh:mm:ss:fff");
				item.SubItems.Add("接收");
				listView1.Items.Add(item);

			} ,null);

		}
	}
}
